<template>
  <div class="game-board">
    <!-- 顶部导航 -->
    <div class="game-header">
      <div class="game-title">
        <span @click="showSetupModal = true" class="btn btn-primary">开局</span>
        <!-- <span class="btn btn-primary">暂停</span> -->
      </div>

      <!-- 游戏信息区域 -->
      <div v-if="isGameActive" class="game-info-header">
        <!-- 级牌显示 -->
        <div v-if="gameState.config.trumpCard" class="trump-display">
          <span class="trump-label">级牌:</span>
          <PokerCard
            :card="gameState.config.trumpCard"
            size="tiny"
            :selectable="false"
          />
        </div>

        <!-- 轮次信息 -->
        <!-- <div class="round-display">
          <span class="round-label">轮次:</span>
          <span class="round-value">{{ gameState.currentRound }}</span>
        </div> -->

        <!-- 队伍信息
        <div class="team-display">
          <div class="team-item">
            <span class="team-label">队伍0:</span>
            <span class="team-members">玩家1 & 玩家3</span>
          </div>
          <div class="team-item">
            <span class="team-label">队伍1:</span>
            <span class="team-members">AI & 玩家2</span>
          </div>
        </div> -->

        <!-- 首次出牌玩家 -->
        <div
          v-if="gameState.config.firstPlayer !== null"
          class="first-player-display"
        >
          <span class="first-player-label">首次出牌:</span>
          <span class="first-player-name">{{
            getPlayerName(gameState.config.firstPlayer)
          }}</span>
        </div>

        <!-- 出牌历史按钮 -->
        <button
          class="btn btn-secondary history-btn"
          @click="showAllHistoryModal = true"
        >
          📜 出牌历史 ({{ gameState.history.length }})
        </button>
      </div>
    </div>

    <!-- 游戏区域 -->
    <div class="game-area">
      <!-- 玩家2 (上方) -->
      <div class="player-position player-position--top">
        <PlayerArea
          v-if="topPlayer"
          ref="topPlayerRef"
          :player="topPlayer as any"
          :can-play="canPlayerPlay(topPlayer.id)"
          :show-play-button="shouldShowPlayButton(topPlayer)"
          :can-pass-player="canPlayerPass(topPlayer.id)"
          :history="gameState.history"
          :trump-card="gameState.config.trumpCard"
          @play-cards="handlePlayerPlay"
          @pass="handlePlayerPass"
          @mark-finished="handleMarkFinished"
        />
      </div>

      <!-- 左右玩家容器 -->
      <div class="middle-row">
        <!-- 玩家3 (左方) -->
        <div class="player-position player-position--left">
          <PlayerArea
            v-if="leftPlayer"
            ref="leftPlayerRef"
            :player="leftPlayer as any"
            :can-play="canPlayerPlay(leftPlayer.id)"
            :show-play-button="shouldShowPlayButton(leftPlayer)"
            :can-pass-player="canPlayerPass(leftPlayer.id)"
            :history="gameState.history"
            :trump-card="gameState.config.trumpCard"
            @play-cards="handlePlayerPlay"
            @pass="handlePlayerPass"
            @mark-finished="handleMarkFinished"
          />
        </div>

        <!-- 中央区域 -->
        <div class="center-area">
          <!-- 游戏结束提示 -->
          <div v-if="gameState.gamePhase === 'finished'" class="game-over">
            <div class="game-over-title">🎉 游戏结束 🎉</div>
            <div class="game-over-winner">
              队伍{{ gameState.winnerTeamId }}获胜！
            </div>
            <div class="game-over-players">
              <div v-for="player in getWinnerPlayers()" :key="player.id">
                {{ player.name }}
              </div>
            </div>
            <button class="btn btn-primary" @click="showSetupModal = true">
              重新开始
            </button>
          </div>

          <!-- AI状态显示 -->
          <div v-else class="center-actions">
            <div v-if="isWaitingAI" class="ai-status">
              <div class="ai-thinking-animation">🤔</div>
              <div>AI思考中...</div>
            </div>
          </div>
        </div>

        <!-- 玩家1 (右方) -->
        <div class="player-position player-position--right">
          <PlayerArea
            v-if="rightPlayer"
            ref="rightPlayerRef"
            :player="rightPlayer as any"
            :can-play="canPlayerPlay(rightPlayer.id)"
            :show-play-button="shouldShowPlayButton(rightPlayer)"
            :can-pass-player="canPlayerPass(rightPlayer.id)"
            :history="gameState.history"
            :trump-card="gameState.config.trumpCard"
            @play-cards="handlePlayerPlay"
            @pass="handlePlayerPass"
            @mark-finished="handleMarkFinished"
          />
        </div>
      </div>

      <!-- AI玩家 (下方) -->
      <div class="player-position player-position--bottom">
        <PlayerArea
          v-if="bottomPlayer"
          ref="bottomPlayerRef"
          :player="bottomPlayer as any"
          :is-current-user="bottomPlayer.type === 'human'"
          :can-play="canPlayerPlay(bottomPlayer.id)"
          :show-play-button="shouldShowPlayButton(bottomPlayer)"
          :can-pass-player="canPlayerPass(bottomPlayer.id)"
          :is-ai-thinking="isWaitingAI && bottomPlayer.isActive"
          :ai-suggested-cards="aiSuggestedCards"
          :ai-should-pass="aiShouldPass"
          :ai-has-error="aiHasError"
          :ai-error-message="aiErrorMessage"
          :history="gameState.history"
          :trump-card="gameState.config.trumpCard"
          @play-cards="handlePlayerPlay"
          @pass="handlePlayerPass"
          @mark-finished="handleMarkFinished"
        />
      </div>

      <!-- AI手牌区域 - 始终显示在底部 -->
      <div v-if="isGameActive && aiPlayerCards.length > 0" class="ai-hand-area">
        <div class="ai-hand-header">
          <span class="ai-hand-title"
            >{{ getAIPlayer?.name || 'AI玩家' }} 的手牌</span
          >
          <span class="ai-hand-count">({{ aiPlayerCards.length }}张)</span>
          <span v-if="showAIHandCardArea" class="selection-hint">
            已选择: {{ aiSelectedCards.length }} 张
          </span>
        </div>

        <div class="hand-cards-grid">
          <PokerCard
            v-for="card in aiPlayerCards"
            :key="card.id"
            :card="card"
            :selected="aiSelectedCards.some((c) => c.id === card.id)"
            size="small"
            :class="{ clickable: showAIHandCardArea }"
            @click="showAIHandCardArea ? handleAICardClick(card) : null"
          />
        </div>

        <div v-if="showAIHandCardArea" class="selection-actions">
          <button
            class="btn btn-success"
            :disabled="!canConfirmAIPlay"
            @click="handleConfirmAIPlay"
          >
            确认出牌 ({{ aiSelectedCards.length }}张)
          </button>
          <button
            v-if="canPlayerPass(0) && aiSelectedCards.length === 0"
            class="btn btn-secondary"
            @click="handleConfirmAIPlay"
          >
            过牌
          </button>
          <button class="btn btn-secondary" @click="handleCancelAIPlay">
            取消
          </button>
        </div>
      </div>

      <!-- 游戏结束提示 -->
      <div v-if="isGameActive && isGameFinished" class="game-finished-notice">
        <div class="finished-content">
          <span class="finished-icon">🎉</span>
          <span class="finished-text">当前牌局已结束</span>
          <span class="finished-icon">🎉</span>
        </div>
      </div>
    </div>

    <!-- 游戏设置弹框 -->
    <GameSetupModal
      :visible="showSetupModal"
      @confirm="handleGameStart"
      @cancel="showSetupModal = false"
    />

    <!-- 完整历史记录弹窗 -->
    <AllHistoryModal
      :visible="showAllHistoryModal"
      :history="gameState.history"
      :trump-card="gameState.config.trumpCard"
      @close="showAllHistoryModal = false"
    />

    <!-- 游戏结束弹窗 -->
    <GameEndModal
      :visible="showGameEndModal"
      :ranks="gameState.ranks"
      :players="gameState.players"
      @close="showGameEndModal = false"
      @new-game="handleNewGame"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useGameState } from '../composables/useGameState'
import { Card } from '../types/card'
import { GameConfig, PlayerType, GamePhase } from '../types/game'
import PlayerArea from './PlayerArea.vue'
import PokerCard from './PokerCard.vue'
import GameSetupModal from './GameSetupModal.vue'
import AllHistoryModal from './AllHistoryModal.vue'
import GameEndModal from './GameEndModal.vue'
import { sortCardsByGuandanRules } from '../utils/cardUtils'

// 组合式函数
const {
  gameState,
  getCurrentPlayer,
  getAIPlayer,
  isGameActive,
  isWaitingAI,
  canConfirmAIPlay,
  startGame,
  playCards,
  selectAICard,
  clearAISelection,
  confirmAIPlay,
  canPass,
  markPlayerFinished,
} = useGameState()

// 响应式数据
const showSetupModal = ref(false)
const showAllHistoryModal = ref(false)
const showGameEndModal = ref(false)

// PlayerArea组件的引用
const topPlayerRef = ref<InstanceType<typeof PlayerArea> | null>(null)
const rightPlayerRef = ref<InstanceType<typeof PlayerArea> | null>(null)
const bottomPlayerRef = ref<InstanceType<typeof PlayerArea> | null>(null)
const leftPlayerRef = ref<InstanceType<typeof PlayerArea> | null>(null)

// 计算属性 - 获取各位置的玩家
const topPlayer = computed(() =>
  gameState.players.find((p: any) => p.position === 'top')
)

const rightPlayer = computed(() =>
  gameState.players.find((p: any) => p.position === 'right')
)

const bottomPlayer = computed(() =>
  gameState.players.find((p: any) => p.position === 'bottom')
)

const leftPlayer = computed(() =>
  gameState.players.find((p: any) => p.position === 'left')
)

// 检查游戏是否结束
const isGameFinished = computed(() => {
  return gameState.gamePhase === GamePhase.FINISHED
})

// AI玩家手牌 (用于展示)
const aiPlayerCards = computed(() => {
  console.log('计算aiPlayerCards:', {
    isGameActive: isGameActive.value,
    aiPlayer: getAIPlayer.value,
    configAiCards: gameState.config.aiCards?.length || 0,
  })

  if (!isGameActive.value) {
    console.log('游戏未激活，返回空数组')
    return []
  }

  // 从AI玩家的实际手牌中获取
  const aiPlayer = getAIPlayer.value

  // 如果AI玩家已经出完牌，返回空数组
  if (aiPlayer && aiPlayer.isFinished) {
    console.log('AI玩家已出完牌，返回空数组')
    return []
  }

  let cards: Card[] = []

  if (aiPlayer && aiPlayer.handCards.length > 0) {
    console.log('从AI玩家获取手牌:', aiPlayer.handCards.length)
    cards = aiPlayer.handCards
  }
  // 如果AI玩家没有手牌，则从配置中获取（仅在游戏刚开始时）
  else if (gameState.config.aiCards && gameState.config.aiCards.length > 0) {
    console.log('从配置获取AI手牌:', gameState.config.aiCards.length)
    cards = gameState.config.aiCards
  } else {
    console.log('没有找到AI手牌，返回空数组')
    return []
  }

  // 按照掼蛋规则排序
  return sortCardsByGuandanRules(cards, gameState.config.trumpCard)
})

// 检查是否显示AI手牌选择区域
const showAIHandCardArea = computed(() => {
  if (!isGameActive.value) return false

  const currentPlayer = getCurrentPlayer.value
  return (
    currentPlayer &&
    currentPlayer.type === PlayerType.AI &&
    currentPlayer.isActive
  )
})

// AI选择的卡牌
const aiSelectedCards = computed(() => {
  return gameState.aiPlaySelection.selectedCards
})

// 方法
const canPlayerPlay = (playerId: number): boolean => {
  if (!isGameActive.value) return false

  const player = gameState.players.find((p: any) => p.id === playerId)
  if (!player) return false

  return player.isActive && player.type === PlayerType.HUMAN
}

// 判断是否显示出牌按钮
const shouldShowPlayButton = (player: any): boolean => {
  if (!isGameActive.value) return false

  // 如果是首次出牌玩家，显示按钮
  if (gameState.config.firstPlayer === player.id) {
    return true
  }

  // 如果不是AI玩家，且游戏已开始，显示按钮
  return player.type === PlayerType.HUMAN
}

// 获取AI建议的牌
const aiSuggestedCards = computed(() => {
  return gameState.aiPlaySelection.selectedCards || []
})

// AI是否建议过牌
const aiShouldPass = computed(() => {
  return gameState.aiPlaySelection.shouldPass || false
})

// AI接口是否出错
const aiHasError = computed(() => {
  return gameState.aiPlaySelection.hasError || false
})

// AI错误信息
const aiErrorMessage = computed(() => {
  return gameState.aiPlaySelection.errorMessage || ''
})

// 获取玩家名称
const getPlayerName = (playerId: number): string => {
  const player = gameState.players.find((p: any) => p.id === playerId)
  return player ? player.name : '未知玩家'
}

// 获取获胜玩家列表
const getWinnerPlayers = () => {
  if (gameState.winnerTeamId === null) return []
  return gameState.players.filter(
    (p: any) => p.teamId === gameState.winnerTeamId
  )
}

// 检查玩家是否可以过牌
const canPlayerPass = (playerId: number): boolean => {
  return canPass(playerId)
}

const handlePlayerPlay = (playerId: number, cards: Card[]) => {
  console.log('GameBoard - handlePlayerPlay 被调用', {
    playerId,
    cardsCount: cards.length,
  })
  try {
    playCards(playerId, cards)

    // 出牌成功后，关闭对应玩家的选择器
    console.log('GameBoard - 出牌成功，准备关闭选择器', { playerId })
    closePlayerCardSelector(playerId)
  } catch (error) {
    console.error('GameBoard - 出牌失败:', error)
    alert(`出牌失败: ${error instanceof Error ? error.message : '未知错误'}`)
    // 出牌失败时不关闭选择器，让玩家可以继续调整
  }
}

// 关闭指定玩家的卡牌选择器
const closePlayerCardSelector = (playerId: number) => {
  // 根据SEAT_POSITIONS的映射：玩家0(下)、玩家1(右)、玩家2(上)、玩家3(左)
  const playerRefs = [
    { id: 0, ref: bottomPlayerRef }, // AI玩家 (下方)
    { id: 1, ref: rightPlayerRef }, // 玩家1 (右方)
    { id: 2, ref: topPlayerRef }, // 玩家2 (上方)
    { id: 3, ref: leftPlayerRef }, // 玩家3 (左方)
  ]

  const playerRef = playerRefs.find((p) => p.id === playerId)
  if (playerRef && playerRef.ref.value) {
    console.log(`关闭玩家${playerId}的卡牌选择器`)
    playerRef.ref.value.closeCardSelector()
  } else {
    console.warn(`未找到玩家${playerId}的ref或ref.value为空`)
  }
}

const handlePlayerPass = (playerId: number) => {
  try {
    playCards(playerId, []) // 空数组表示过牌
  } catch (error) {
    console.error('过牌失败:', error)
    alert(`过牌失败: ${error instanceof Error ? error.message : '未知错误'}`)
  }
}

const handleMarkFinished = (playerId: number) => {
  try {
    markPlayerFinished(playerId)
    console.log(`玩家${playerId}已标记为出完牌`)
  } catch (error) {
    console.error('标记玩家出完失败:', error)
    alert(`标记失败: ${error instanceof Error ? error.message : '未知错误'}`)
  }
}

const handleNewGame = () => {
  showGameEndModal.value = false
  showSetupModal.value = true
}

// 监听AI玩家是否出完牌，自动显示游戏结束弹窗
watch(
  () => getAIPlayer.value?.isFinished,
  (isFinished) => {
    if (isFinished) {
      console.log('AI玩家已出完牌，显示游戏结束弹窗')
      // 延迟一下显示，让用户看到最后的状态
      setTimeout(() => {
        showGameEndModal.value = true
      }, 1000)
    }
  }
)

// 监听游戏阶段变化，当游戏结束时显示弹窗
watch(
  () => gameState.gamePhase,
  (phase: GamePhase) => {
    if (phase === GamePhase.FINISHED) {
      console.log('游戏结束，显示游戏结束弹窗')
      // 延迟一下显示，让用户看到最后的状态
      setTimeout(() => {
        showGameEndModal.value = true
      }, 1000)
    }
  }
)

// const callAIService = async () => {
//   try {
//     console.log('调用AI服务...')

//     // 调用AI决策接口
//     const { getAIDecision } = await import('../services/aiService')
//     const aiResponse = await getAIDecision(gameState)

//     console.log('AI决策响应:', aiResponse)

//     if (aiResponse.success && aiResponse.data.recommendedCards.length > 0) {
//       // 从AI玩家手牌中找到对应的扑克牌
//       const aiPlayer = getAIPlayer.value
//       if (aiPlayer) {
//         const recommendedCards = findCardsInHand(
//           aiPlayer.handCards,
//           aiResponse.data.recommendedCards
//         )

//         if (
//           recommendedCards.length === aiResponse.data.recommendedCards.length
//         ) {
//           // 所有推荐的牌都在AI手牌中找到，执行出牌
//           handlePlayerPlay(aiPlayer.id, recommendedCards)

//           // 显示AI的推理说明
//           if (aiResponse.data.reasoning) {
//             console.log('AI推理:', aiResponse.data.reasoning)
//             // 可以在界面上显示AI的推理过程
//           }
//         } else {
//           console.warn('AI推荐的牌在手牌中未找到完整匹配，执行降级处理')
//           // 降级处理：随机出牌
//           handleAIFallback(aiPlayer)
//         }
//       }
//     } else {
//       // AI选择过牌
//       const aiPlayer = getAIPlayer.value
//       if (aiPlayer) {
//         handlePlayerPlay(aiPlayer.id, [])
//       }
//     }
//   } catch (error) {
//     console.error('AI服务调用失败:', error)

//     // 降级处理：AI随机出牌或过牌
//     const aiPlayer = getAIPlayer.value
//     if (aiPlayer) {
//       if (aiPlayer.handCards.length > 0 && Math.random() > 0.3) {
//         // 70%概率随机出一张牌
//         const randomCard =
//           aiPlayer.handCards[
//             Math.floor(Math.random() * aiPlayer.handCards.length)
//           ]
//         handlePlayerPlay(aiPlayer.id, [randomCard])
//       } else {
//         // 30%概率过牌
//         handlePlayerPlay(aiPlayer.id, [])
//       }
//     }

//     throw error
//   }
// }

const handleGameStart = (config: GameConfig) => {
  try {
    startGame(config)
    showSetupModal.value = false
  } catch (error) {
    console.error('游戏开始失败:', error)
    alert(
      `游戏开始失败: ${error instanceof Error ? error.message : '未知错误'}`
    )
  }
}

// AI卡牌点击处理（选择/取消选择）
const handleAICardClick = (card: Card) => {
  try {
    selectAICard(card) // selectAICard内部会处理选择/取消选择的逻辑
  } catch (error) {
    console.error('AI卡牌选择失败:', error)
    alert(
      `AI卡牌选择失败: ${error instanceof Error ? error.message : '未知错误'}`
    )
  }
}

// 确认AI出牌处理
const handleConfirmAIPlay = () => {
  try {
    confirmAIPlay()
  } catch (error) {
    console.error('确认AI出牌失败:', error)
    alert(
      `确认AI出牌失败: ${error instanceof Error ? error.message : '未知错误'}`
    )
  }
}

// 取消AI选择处理
const handleCancelAIPlay = () => {
  try {
    clearAISelection()
  } catch (error) {
    console.error('取消AI选择失败:', error)
  }
}

// // 辅助函数：在手牌中查找对应的卡牌
// const findCardsInHand = (handCards: Card[], targetCards: any[]): Card[] => {
//   const foundCards: Card[] = []

//   for (const targetCard of targetCards) {
//     const foundCard = handCards.find(
//       (handCard) =>
//         handCard.suit === targetCard.suit && handCard.rank === targetCard.rank
//     )
//     if (foundCard) {
//       foundCards.push(foundCard)
//     }
//   }

//   return foundCards
// }

// AI降级处理
// const handleAIFallback = (aiPlayer: any) => {
//   if (aiPlayer.handCards.length > 0 && Math.random() > 0.3) {
//     // 70%概率随机出一张牌
//     const randomCard =
//       aiPlayer.handCards[Math.floor(Math.random() * aiPlayer.handCards.length)]
//     handlePlayerPlay(aiPlayer.id, [randomCard])
//   } else {
//     // 30%概率过牌
//     handlePlayerPlay(aiPlayer.id, [])
//   }
// }
</script>

<style scoped>
.game-board {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(
    135deg,
    var(--poker-green) 0%,
    var(--poker-dark-green) 100%
  );
}

/* 游戏头部 */
.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-lg);
  background: rgba(0, 0, 0, 0.2);
  color: white;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.game-info-header {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

.trump-display {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.trump-label {
  color: #ffd700;
  font-weight: bold;
  font-size: 14px;
}

.first-player-display {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.first-player-label {
  color: #87ceeb;
  font-weight: bold;
  font-size: 14px;
}

.first-player-name {
  color: #ffd700;
  font-weight: bold;
  background: rgba(255, 215, 0, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid #ffd700;
}

/* 轮次显示 */
.round-display {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.round-label {
  color: #87ceeb;
  font-weight: bold;
  font-size: 14px;
}

.round-value {
  color: white;
  font-weight: bold;
  background: rgba(135, 206, 235, 0.2);
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid #87ceeb;
}

/* 队伍显示 */
.team-display {
  display: flex;
  gap: var(--spacing-md);
  align-items: center;
}

.team-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.team-label {
  color: #98fb98;
  font-weight: bold;
  font-size: 14px;
}

.team-members {
  color: white;
  font-size: 13px;
  background: rgba(152, 251, 152, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid #98fb98;
}

/* 历史按钮 */
.history-btn {
  padding: 6px 12px;
  font-size: 14px;
  font-weight: bold;
  background: rgba(135, 206, 235, 0.2);
  border: 1px solid #87ceeb;
  color: white;
  cursor: pointer;
  border-radius: 4px;
  transition: var(--transition);
}

.history-btn:hover {
  background: rgba(135, 206, 235, 0.3);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(135, 206, 235, 0.3);
}

.game-title {
  display: flex;
  gap: var(--spacing-lg);
  font-weight: bold;
}
.game-title span {
  background-color: #34495e;
}

.game-status {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.game-actions {
  display: flex;
  gap: var(--spacing-sm);
}

/* 游戏区域 */
.game-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: var(--spacing-lg);
  gap: var(--spacing-lg);
}

/* AI手牌展示区域 */
.ai-cards-display {
  background: rgba(0, 0, 0, 0.3);
  border: 2px solid #ffd700;
  border-radius: var(--border-radius);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-md);
}

.ai-cards-header {
  margin-bottom: var(--spacing-sm);
  text-align: center;
}

.ai-cards-label {
  color: #ffd700;
  font-weight: bold;
  font-size: 16px;
}

.ai-cards-container {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-xs);
  justify-content: center;
  max-height: 120px;
  overflow-y: auto;
}

.player-position {
  display: flex;
  justify-content: center;
  width: 300px;
}

.player-position--top,
.player-position--bottom {
  width: 100%;
}

.player-position--top > *,
.player-position--bottom > *,
.player-position--left > *,
.player-position--right > * {
  width: 300px;
  max-width: 100%;
}

.middle-row {
  flex: 1;
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

.hand-label {
  color: #ffd700;
}
.center-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: var(--spacing-lg);
}

.center-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-md);
}

.confirm-btn {
  padding: var(--spacing-md) var(--spacing-xl);
  font-size: 16px;
  font-weight: bold;
  min-width: 200px;
}

.ai-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-sm);
  color: white;
}

.ai-thinking-animation {
  font-size: 24px;
  animation: bounce 1s infinite;
}

@keyframes bounce {
  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

.game-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-xs);
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.team-info {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
  margin-top: var(--spacing-sm);
  padding: var(--spacing-sm);
  background: rgba(0, 0, 0, 0.3);
  border-radius: var(--border-radius);
  font-size: 12px;
}

/* 游戏结束界面 */
.game-over {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-lg);
  padding: var(--spacing-xl);
  background: rgba(0, 0, 0, 0.8);
  border: 3px solid #ffd700;
  border-radius: var(--border-radius-lg);
  animation: gameOverAppear 0.5s ease-out;
}

@keyframes gameOverAppear {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.game-over-title {
  font-size: 32px;
  font-weight: bold;
  color: #ffd700;
  text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
}

.game-over-winner {
  font-size: 24px;
  color: white;
  font-weight: bold;
}

.game-over-players {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
  color: #4caf50;
  font-size: 18px;
}

/* 顶部历史记录容器 */
.history-container-top {
  width: 100%;
  padding: 0 var(--spacing-md);
  margin-bottom: var(--spacing-sm);
}

.history-container {
  width: 100%;
  max-width: 400px;
  margin-top: var(--spacing-sm);
}

/* AI手牌区域 - 始终显示 */
.ai-hand-area {
  background: rgba(0, 0, 0, 0.8);
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-md);
  margin-top: var(--spacing-md);
  transition: all 0.3s ease;
}

.ai-hand-area:has(.selection-actions) {
  border-color: rgba(253, 126, 20, 0.5);
  background: rgba(0, 0, 0, 0.95);
  box-shadow: 0 -4px 20px rgba(253, 126, 20, 0.3);
}

.ai-hand-header {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-md);
  padding-bottom: var(--spacing-sm);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.ai-hand-title {
  color: white;
  font-weight: bold;
  font-size: 16px;
}

.ai-hand-count {
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
}

.selection-hint {
  color: var(--btn-primary);
  font-weight: bold;
  font-size: 14px;
  margin-left: auto;
  background: rgba(253, 126, 20, 0.2);
  padding: 4px 12px;
  border-radius: 4px;
}

.hand-cards-grid {
  display: flex;
  gap: var(--spacing-sm);
  justify-content: center;
  flex-wrap: wrap;
  padding: var(--spacing-sm);
  min-height: 80px;
  max-height: 180px;
  overflow-y: auto;
}

.hand-cards-grid .clickable {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.hand-cards-grid .clickable:hover {
  transform: translateY(-8px);
}

.selection-actions {
  display: flex;
  justify-content: center;
  gap: var(--spacing-md);
  margin-top: var(--spacing-md);
  padding-top: var(--spacing-md);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

/* 游戏结束提示 */
.game-finished-notice {
  background: linear-gradient(
    135deg,
    rgba(253, 126, 20, 0.9),
    rgba(255, 193, 7, 0.9)
  );
  border: 3px solid rgba(255, 215, 0, 0.8);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-lg);
  margin-top: var(--spacing-md);
  box-shadow:
    0 4px 20px rgba(253, 126, 20, 0.5),
    0 0 40px rgba(255, 193, 7, 0.3);
  animation: finishedPulse 2s ease-in-out infinite;
}

.finished-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-md);
}

.finished-text {
  font-size: 24px;
  font-weight: bold;
  color: #fff;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  letter-spacing: 2px;
}

.finished-icon {
  font-size: 32px;
  animation: finishedBounce 1s ease-in-out infinite;
}

@keyframes finishedPulse {
  0%,
  100% {
    transform: scale(1);
    box-shadow:
      0 4px 20px rgba(253, 126, 20, 0.5),
      0 0 40px rgba(255, 193, 7, 0.3);
  }
  50% {
    transform: scale(1.02);
    box-shadow:
      0 6px 30px rgba(253, 126, 20, 0.7),
      0 0 60px rgba(255, 193, 7, 0.5);
  }
}

@keyframes finishedBounce {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .game-area {
    padding: var(--spacing-md);
    gap: var(--spacing-md);
  }

  .middle-row {
    gap: var(--spacing-md);
  }

  .player-position--left,
  .player-position--right {
    width: 150px;
  }

  .confirm-btn {
    min-width: 150px;
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .game-header {
    flex-direction: column;
    gap: var(--spacing-sm);
    padding: var(--spacing-sm);
  }

  .game-title {
    gap: var(--spacing-md);
  }

  .middle-row {
    flex-direction: column;
    gap: var(--spacing-sm);
  }

  .player-position--left,
  .player-position--right {
    width: 100%;
  }

  .hand-cards {
    gap: 2px;
  }

  .confirm-btn {
    min-width: 120px;
    padding: var(--spacing-sm) var(--spacing-md);
  }
}
</style>
